<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Happy ERP</title>
<script type="text/javascript">
    var newProductWin;
    var editProductWin;
    var copyProductWin;
    var currentNode;
    var currentPage = 1;
    var psPageSize = 25 //product setup pagesize
    var totalCount = <%=@totalCount%>;
    var totalPage = 0;
    var productTree;
    var searchKey = null; //用来确认一下，是不是
    Ext.onReady(function () {
        function pageBtnDisable() {
            Ext.getCmp('pfid').disable();
            Ext.getCmp('pvid').disable();
            Ext.getCmp('pnid').disable();
            Ext.getCmp('plid').disable();

        }

        function pageBtnEnable() {
            Ext.getCmp('pfid').enable();
            Ext.getCmp('pvid').enable();
            Ext.getCmp('pnid').enable();
            Ext.getCmp('plid').enable();
        }

        //这是跳页函数
        function paging(i) {
            currentPage = i;
            if (i < 0) {
                currentPage = 1;
            }
            if (totalCount < psPageSize) {
                totalPage = 1
            } else {
                totalPage = (totalCount % psPageSize) > 0 ? Math.floor(totalCount / psPageSize) + 1 : Math.floor(totalCount / psPageSize);
            }

            if (currentPage > totalPage) {
                currentPage = totalPage;
            }
            pageBtnDisable();
            Ext.getCmp('pageNumber').setValue(currentPage);
            dateReload(currentPage);
        }

        //导入相应页数的数据
        function dateReload(currentPage) {
            Ext.Ajax.request({
                url:'/product/getProductCount?' + searchKey,
                success:function (response) {
                    totalCount = parseInt(response.responseText);
                    productTreeStore.getProxy().extraParams.start = (currentPage == 1 ? 0 : (currentPage - 1) * psPageSize - 1);
                    productTreeStore.getProxy().extraParams.limit = psPageSize;
                    productTreeStore.load();
                    refreshPageInfo();
                    pageBtnEnable();
                },
                failure:function () {
                    Ext.MessageBox.alert("提示", "连接数据库错误或连接超时！")
                    pageBtnEnable();
                }
            });
        }

        //Ext.Msg.getDialog().setWidth(400); Ext.toolbar.TextItem
        var pageSubInfo = Ext.create('Ext.toolbar.TextItem', {text:"&nbsp;页 , 共 " + ((totalCount % psPageSize) > 0 ? Math.floor(totalCount / psPageSize) + 1 : Math.floor(totalCount / psPageSize)) + ' 页'});
        var pageTotalInfo = Ext.create('Ext.toolbar.TextItem', {text:'显示第 ' + ((currentPage - 1) * psPageSize > 0 ? Math.floor(currentPage / psPageSize) : 1) + '  条到 ' + currentPage * psPageSize + ' 条记录，一共 ' + totalCount + ' 条'});

        function refreshPageInfo() {
            pageSubInfo.setText("&nbsp;页 , 共 " + ((totalCount % psPageSize) > 0 ? Math.floor(totalCount / psPageSize) + 1 : Math.floor(totalCount / psPageSize)) + ' 页');
            //判断是不是最后一页
            if (currentPage == (Math.floor(totalCount / psPageSize) + 1)) {
                pageTotalInfo.setText('显示第 ' + ((currentPage - 1) * psPageSize > 0 ? Math.floor(currentPage - 1) * psPageSize : 1) + '  条到 ' + totalCount + ' 条记录，一共 ' + totalCount + ' 条');
            } else {
                pageTotalInfo.setText('显示第 ' + ((currentPage - 1) * psPageSize > 0 ? Math.floor(currentPage - 1) * psPageSize : 1) + '  条到 ' + currentPage * psPageSize + ' 条记录，一共 ' + totalCount + ' 条');
            }

        }

        Ext.define('Product', {
            extend:'Ext.data.Model',
            fields:[
                {name:'id', type:'int'},
                {name:'number', type:'string'},
                {name:'name', type:'string'},
                {name:'brand_name', type:'string'},
                {name:'product_type', type:'string'},
                {name:'quantity', type:'string'},
                {name:'spec'},
                {name:'unit'},
                {name:'unit_price'},
                {name:'description'},
                {name:'created_at'},
                {name:'updated_at'}
            ]
        });

        var productTreeStore = Ext.create('Ext.data.TreeStore', {
            //autoDestroy : true,
            model:'Product',
            proxy:{
                type:'ajax',
                url:'/product/getTreeData',
                //url:'/product/getTreeData?start=0&limit='+psPageSize,
                extraParams:{start:'0', limit:psPageSize}
            },
            root:{
                name:'Products',
                id:'0',
                expanded:true
            }
            //folderSort: true
        });

        productTree = Ext.create('Ext.tree.Panel', {
            width:screenWidth - 190,
            height:600,
            store:productTreeStore,
            rootVisible:true,
            autoScroll:true,
            useArrows:true,
            multiSelect:true,
            singleExpand:true,
            title:'树形产品列表',
            //renderTo: 'products_tree_div',
            columns:[
                {
                    text:'ID',
                    width:40,
                    dataIndex:'id'
                },
                {
                    xtype:'treecolumn',
                    text:'名称',
                    width:280,
                    dataIndex:'name'
                },
                {
                    text:'品牌',
                    width:70,
                    dataIndex:'brand_name'
                },
                {
                    text:'编号',
                    width:130,
                    dataIndex:'number'
                },
                {
                    text:'类型',
                    width:80,
                    dataIndex:'product_type'
                },
                {
                    text:'规格',
                    width:80,
                    dataIndex:'spec'
                },
                {
                    text:'销售单价',
                    width:70,
                    align:'right',
                    renderer:Ext.util.Format.numberRenderer('0,000.00'),
                    dataIndex:'unit_price'
                },
                {
                    text:'数量',
                    align:'right',
                    width:60,
                    dataIndex:'quantity'
                },
                {
                    text:'备注',
                    width:260,
                    dataIndex:'description'
                },
                {
                    text:'生成日期',
                    dataIndex:'created_at',
                    width:115
                },
                {
                    text:'修改日期',
                    dataIndex:'updated_at',
                    width:115
                }
            ],
            bbar:[
                {
                    id:'pfid',
                    tooltip:'第一页',
                    iconCls:'page-first',
                    listeners:{
                        'click':function () {
                            currentPage = 1;
                            paging(currentPage);
                        }
                    }
                },
                {
                    id:'pvid',
                    tooltip:'上一页',
                    iconCls:'page-prev',
                    listeners:{
                        'click':function () {
                            if (currentPage > 1) {
                                currentPage = currentPage - 1;
                                paging(currentPage);
                            }
                        }
                    }
                },
                '-',
                Ext.create('Ext.toolbar.TextItem', {text:'第 '}),
                {
                    id:'pageNumber',
                    xtype:'numberfield',
                    emptyText:currentPage > 1 ? currentPage : 1,
                    //data: 6,
                    enableKeyEvents:true,
                    decimalPrecision:0,
                    minValue:0,
                    allowDecimals:false,
                    style:'color:#000;',
                    selectOnFocus:true,
                    width:30,
                    listeners:{
                        keypress:function (obj, evt) {
                            if (evt.getKey() == Ext.EventObject.RETURN) {
                                currentPage = this.getValue()
                                paging(currentPage);
                            }
                        }
                    }
                },
                pageSubInfo,
                '-',
                {
                    id:'pnid',
                    tooltip:'下一页',
                    iconCls:'page-next',
                    listeners:{
                        'click':function () {
                            paging(currentPage + 1);
                        }
                    }
                },
                {
                    id:'plid',
                    tooltip:'最后页',
                    iconCls:'page-last',
                    listeners:{
                        'click':function () {
                            currentPage = ((totalCount % psPageSize) > 0 ? Math.floor(totalCount / psPageSize) + 1 : Math.floor(totalCount / psPageSize))
                            paging(currentPage);
                        }
                    }
                },
                '->',
                pageTotalInfo
            ]
        });

        productTree.on("itemcontextmenu", function (view, record, item, index, e, options) {
            e.preventDefault();
            productRightMenu.showAt(e.getXY());
            //productRightMenu.show(node.ui.getAnchor());
            currentNode = record;
            nodeId = record.get('id');
            //window.status = currentNode.id;
            //alert(typeof(currentNode.id)==="string");
            //如果为叶子，则禁止刷新功能。nodeId为0，代表根。
            if (nodeId == 0 || nodeId == 'NaN') {
                editProductMenuItem.setDisabled(true);
                addProductMenuItem.setDisabled(false);
                delProductMenuItem.setDisabled(true);
            } else {
                addProductMenuItem.setDisabled(true);
                editProductMenuItem.setDisabled(false);
            }
        }, this);

        //右键菜单
        var addProductMenuItem = Ext.create('Ext.menu.Item', {
            text:'添加产品或套装',
            iconCls:'addItem',
            handler:rightMenuProductTreeFn
        });
        var editProductMenuItem = Ext.create('Ext.menu.Item', {
            text:'编辑产品或套装',
            iconCls:'editItem',
            handler:rightMenuProductTreeFn
        });
        var copyProductMenuItem = Ext.create('Ext.menu.Item', {
            text:'复制产品',
            iconCls:'editItem',
            handler:rightMenuProductTreeFn
        });
        var delProductMenuItem = Ext.create('Ext.menu.Item', {
            text:'删除',
            iconCls:'remove',
            handler:rightMenuProductTreeFn
        });
        var refreshMenuItem = Ext.create('Ext.menu.Item', {
            text:'刷新',
            iconCls:'refresh',
            handler:rightMenuProductTreeFn
        });

        var productRightMenu = Ext.create('Ext.menu.Menu', {
            //id: 'product_right_menu',
            items:[
                addProductMenuItem,
                editProductMenuItem,
                '-',
                copyProductMenuItem,
                '-',
                delProductMenuItem,
                '-',
                refreshMenuItem
            ]});

        function rightMenuProductTreeFn(item, e) {
            if (item.text == "添加产品或套装") {
                newProductWin = Ext.create('Ext.window.Window', {
                    layout:'fit',
                    width:960,
                    height:640,
                    closeAction:'destroy',
                    plain:true,
                    modal:true,
                    constrain:true,
                    //modal: true,
                    title:'添加产品或套装',
                    autoLoad:{
                        url:"/product/newProduct",
                        scripts:true
                    }
                });
                newProductWin.on("destroy", function () {
                    //刷新整个树
                    //tree.root.load();
                    productComponentsDS.removeAll();
                });
                newProductWin.resizable = false;
                newProductWin.show();
            } else if (item.text == "编辑产品或套装") {
                editProductWin = Ext.create('Ext.window.Window', {
                    layout:'fit',
                    width:960,
                    height:640,
                    closeAction:'destroy',
                    plain:true,
                    modal:true,
                    constrain:true,
                    //modal: true,
                    title:'编辑产品或套装',
                    autoLoad:{
                        url:"/product/editProduct?id=" + nodeId,
                        scripts:true
                    }
                });
                editProductWin.on("destroy", function () {
                    productComponentsDS.removeAll();
                });
                editProductWin.resizable = false;
                editProductWin.show();
            }else if (item.text == "复制产品") {
                copyProductWin = Ext.create('Ext.window.Window', {
                    layout:'fit',
                    width:960,
                    height:640,
                    closeAction:'destroy',
                    plain:true,
                    modal:true,
                    constrain:true,
                    //modal: true,
                    title:'复制产品为新产品',
                    autoLoad:{
                        url:"/product/copyProduct?id=" + nodeId,
                        scripts:true
                    }
                });
                copyProductWin.on("destroy", function () {
                    productComponentsDS.removeAll();
                });
                copyProductWin.resizable = false;
                copyProductWin.show();
            } else if (item.text == "刷新") {
                if (currentNode.isLeaf()) {
                    productTreeStore.load({
                        node:currentNode.parentNode
                    });
                } else {
                    productTreeStore.load({
                        node:currentNode
                    });
                }
            } else if (item.text == "删除") {
                Ext.MessageBox.confirm("提示", "你确认删除 \"" + currentNode.get('name') + "\" 吗？", function (btn) {
                    if (btn == "yes") {
                        Ext.Ajax.request({
                            url:'/product/destroy?id=' + currentNode.get('id'),
                            success:function (response) {
                                Ext.MessageBox.show({
                                    title:'消息',
                                    msg:Ext.JSON.decode(response.responseText).info,
                                    buttons:Ext.MessageBox.OK,
                                    icon:Ext.MessageBox.WARNING
                                });
                            },
                            failure:function (result, request) {
                                Ext.MessageBox.show({
                                    title:'消息',
                                    msg:"通讯失败，请从新操作",
                                    buttons:Ext.MessageBox.OK,
                                    icon:Ext.MessageBox.WARNING
                                });
                            },
                            method:'GET'
                        });
                    } else {
                        //alert("no");
                    }
                });
            }
        }


        //tree.render();

        var productName = Ext.create('Ext.form.field.Text', {
            fieldLabel:'产品名称或编号',
            name:'name',
            anchor:'95%'
        });

        var productTypeStore = Ext.create('Ext.data.Store', {
            //autoDestroy : true,
            model:'ProductTypeModel',
            proxy:{
                type:'ajax',
                url:"/product_type/getAllProductTypes?for_cbb=true",
                reader:{
                    type:'json',
                    root:'root',
                    totalProperty:'totalProperty'// 数据集记录总数
                }
            }//,
            //pageSize : pageSize,
            //autoLoad : true
        });

        //产品类型
        var productType = Ext.create('Ext.form.ComboBox', {
            store:productTypeStore,
            fieldLabel:'产品类别',
            valueField:'id',
            displayField:'name',
            name:'product_type_id', //如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText:'请选择...',
            loadingText:'搜索中...',
            anchor:'100%',
            readOnly:false,
            minChars:0
        });

        var brandStore = Ext.create('Ext.data.Store', {
            //autoDestroy : true,
            model:'BrandModel',
            proxy:{
                type:'ajax',
                url:"/brand/getAllBrands?for_cbb=true",
                reader:{
                    type:'json',
                    root:'root',
                    totalProperty:'totalProperty'// 数据集记录总数
                }
            }//,
            //pageSize : pageSize,
            //autoLoad : true
        });

        //品牌
        var brand = Ext.create('Ext.form.ComboBox', {
            store:brandStore,
            fieldLabel:'品牌',
            allowBlank:false,
            blankText:"品牌必须选择",
            valueField:'id',
            displayField:'name',
            name:'brand_id', //如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText:'请选择...',
            editable:false,
            loadingText:'搜索中...',
            anchor:'95%',
            readOnly:false,
            minChars:0
        });

        var searchButton = Ext.create('Ext.Button', {
            text:'搜索',
            iconCls:'finding',
            width:70,
            handler:function () {
                //重新把页数初始化
                productTreeStore.getProxy().extraParams.start = 0;
                productTreeStore.getProxy().extraParams.limit = psPageSize;

                searchKey = 'name=' + encodeURIComponent(productName.getValue());
                productTreeStore.getProxy().extraParams.name = productName.getValue();//encodeURIComponent(productName.getValue());
                if (productType.getValue() != null) {
                    searchKey = searchKey + "&product_type_id=" + productType.getValue();
                    productTreeStore.getProxy().extraParams.product_type_id = productType.getValue();
                }
                if (brand.getValue() != null) {
                    searchKey = searchKey + "&brand_id=" + brand.getValue();
                    productTreeStore.getProxy().extraParams.brand_id = brand.getValue();
                }
                //productTreeStore.removeAll();

                /*productTreeStore.getProxy().extraParams = {
                 start: 50,
                 limit: 30
                 };
                 productTreeStore.load();*/
                paging(1);
            }
        });

        var clearButton = Ext.create('Ext.Button', {
            text:'清空',
            width:50,
            handler:function () {
                queryFormPanel.form.reset();
                searchKey = null;
            }
        });

        var queryFormPanel = Ext.create('Ext.form.Panel', {
            fieldDefaults:{
                labelWidth:95,
                labelAlign:'right'
            },
            width:screenWidth - 165,
            frame:true,
            border:false,
            items:[
                {
                    xtype:'fieldset',
                    defaults:{width:screenWidth - 190},
                    title:'查询条件',
                    border:true,
                    items:[
                        {
                            layout:'column',
                            xtype:'container',
                            items:[
                                {
                                    columnWidth:.2,
                                    layout:'anchor',
                                    xtype:'container',
                                    items:[productName]
                                },
                                {
                                    columnWidth:.16,
                                    layout:'anchor',
                                    xtype:'container',
                                    labelWidth:60,
                                    items:[productType]
                                },
                                {
                                    columnWidth:.16,
                                    layout:'anchor',
                                    xtype:'container',
                                    labelWidth:60,
                                    items:[brand]
                                },
                                {
                                    columnWidth:.1,
                                    layout:'anchor',
                                    xtype:'container',
                                    items:[searchButton]
                                },
                                {
                                    columnWidth:.2,
                                    layout:'anchor',
                                    xtype:'container',
                                    items:[clearButton]
                                }
                            ]
                        }
                    ]
                }
            ]
        });

        //总的panel
        var workbenchPanel = Ext.create('Ext.form.Panel', {
            width:screenWidth - 165,
            height:700,
            //html: '&lt;empty panel&gt;',
            //cls:'cellpadding:10',
            /*layout: {
             type:'vbox',
             align:'stretch'
             },*/
            frame:false,

            layout:{type:'table', columns:1},

            //bodyStyle: 'padding:15px;align:center',
            //listeners: {
            //expand: showAgileDiagram
            //},
            items:[queryFormPanel, productTree]
        });

        workbenchPanel.render("products_div");

        Ext.define('SaleTypePriceModel', {
            extend:'Ext.data.Model',
            fields:[
                {name:'id'},
                {name:'name'},
                {
                    name:'unit_price', type:'float',
                    convert:function (value, record) {
                        if (value == null || value == undefined || value == '') {
                            return -1;
                        } else {
                            return value;
                        }
                    }
                }
            ]
        });

        saleTypePricesDS = Ext.create('Ext.data.Store', {
            autoDestroy:true,
            model:'SaleTypePriceModel',
            proxy:{
                type:'ajax',
                url:"/product/getPricesById",
                extraParams:{id:0},
                reader:{
                    type:'json',
                    root:'root',
                    totalProperty:'totalProperty'// 数据集记录总数
                }
            }
        });

        Ext.define('ProductComponentModel', {
            extend:'Ext.data.Model',
            fields:[
                {name:'id'},
                {
                    name:'number',
                    mapping:'component.number'
                },
                {
                    name:'name',
                    mapping:'component.name'
                },
                {
                    name:'unit',
                    mapping:'component.unit'
                },
                {
                    name:'spec',
                    mapping:'component.spec'
                },
                {
                    name:'description'
                },
                {
                    name:'unit_price',
                    mapping:'component.unit_price',
                    type:'float'
                },
                {
                    name:'quantity',
                    type:'int'
                },
                {
                    name:'discount',
                    type:'float'
                },
                {
                    name:'product_id',
                    mapping:'component_id',
                    type:'int'
                },
                {
                    name:'amount'
                },
                {
                    name:'is_suit',
                    mapping:'component.is_suit',
                    convert:function (value, record) {
                        if (value == "1") {
                            return "套装";
                        } else if (value == "0") {
                            return "单品";
                        }
                    }
                }
            ]
        });

        productComponentsDS = Ext.create('Ext.data.Store', {
            autoDestroy:true,
            model:'ProductComponentModel',
            proxy:{
                type:'ajax',
                url:'/product/getAllComponentsById',
                extraParams:{id:0},
                reader:{
                    type:'json',
                    root:'root',
                    totalProperty:'totalProperty'// 数据集记录总数
                }
            }
        });

        //产品下拉框模型
        Ext.define('ProductModel', {
            extend:'Ext.data.Model',
            fields:[
                {name:'id', type:'int'},
                {name:'number', type:'string'},
                {name:'name', type:'string'},
                {
                    name:'vendor_id'
                },
                {
                    name:'spec'
                },
                {
                    name:'unit'
                },
                {
                    name:'unit_price'
                },
                {
                    name:'min_quantity'
                },
                {
                    name:'max_quantity'
                },
                {
                    name:'brand_id'
                },
                {
                    name:'product_type_id'
                },
                {
                    name:'is_suit'
                },
                {
                    name:'is_sale'
                },
                {
                    name:'description'
                }
            ]
        });

    });
</script>
</head>
<body>
<div id="products_div"></div>
</body>
</html>
